package com.elinkway.infinitemovies.adapter;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.bean.Episode;
import com.elinkway.infinitemovies.download.DownloadEntity;
import com.elinkway.infinitemovies.download.DownloadJob;
import com.elinkway.infinitemovies.ui.activity.VideoDetailActivity;
import com.elinkway.infinitemovies.utils.ToastUtil;
import com.le123.ysdq.R;
import com.le123.ysdq.databinding.LayoutEpisodePlayItemBinding;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by xiao on 21/4/17.
 *
 * 详情页弹起的下载浮层 适配器
 */
public class DownloadEpisodePlayAdapter extends RecyclerView.Adapter<DownloadEpisodePlayAdapter.EpisodeHolder> {

    private Context mContext;
    private ArrayList<Episode> episodes;
    private String mType;
    private String mPage;
    private LayoutInflater mLayoutInflater;
    private int index;
    private String mSelectProder = "";

    private HashMap<String, Integer> downloadListItems;



    private String site;
    public DownloadEpisodePlayAdapter(Context mContext, ArrayList<Episode> episodes, String type, String page, int index, String site) {
        this.mContext = mContext;
        this.episodes = episodes;
        this.mType = type;
        this.index = index;
        mLayoutInflater = LayoutInflater.from(mContext);
        downloadListItems = new HashMap<String, Integer>();
        this.mPage = page;
        this.site = site;
        initData();
        if (!TextUtils.isEmpty(((VideoDetailActivity)mContext).currentPlayingPorder())) {
            mSelectProder = ((VideoDetailActivity) mContext).currentPlayingPorder();
        }
        updateDownloadedFlagByDB();

    }

    @Override
    public EpisodeHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        return new EpisodeHolder(mLayoutInflater.inflate(R.layout.layout_episode_play_item, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(EpisodeHolder holder, int position) {
        if(holder instanceof EpisodeHolder){
            ((EpisodeHolder)holder).bind(episodes.get(position), position, mContext, mType, mSelectProder, index);
        }
    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }


    public class EpisodeHolder extends RecyclerView.ViewHolder {
        private LayoutEpisodePlayItemBinding mEpisodeBinding;

        public EpisodeHolder(View itemView) {
            super(itemView);
            mEpisodeBinding = DataBindingUtil.bind(itemView);
        }

        public void bind(@NonNull final Episode episode, final int position, final Context context, final String type, String mSelectProder ,final int index) {
            mEpisodeBinding.episodePlayItem.setBackgroundResource(R.drawable.rectangle_round_corner_f5);


            if("list".equals(type)){
                mEpisodeBinding.episodePlayItemNum.setText(episode.getSubName());
                mEpisodeBinding.episodePlayItemNum.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
            }else if("grid".equals(type)){
                mEpisodeBinding.episodePlayItemNum.setText(episode.getPorder());
                mEpisodeBinding.episodePlayItemNum.setGravity(Gravity.CENTER);
            }
            if (mSelectProder.equals(episode.getPorder())) {
                mEpisodeBinding.episodePlayItemNum.setTextColor(context.getResources().getColor(R.color.color_3599f8));
                mEpisodeBinding.episodePlayItemNum.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            } else {
                mEpisodeBinding.episodePlayItemNum.setTextColor(context.getResources().getColor(R.color.blue_black_text_selecter));
                mEpisodeBinding.episodePlayItemNum.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            }

            if ("1".equals(episode.getIsPay())){
                mEpisodeBinding.ispay.setVisibility(View.VISIBLE);
                mEpisodeBinding.episodePlayItemNum.setTextColor(context.getResources().getColor(R.color.color_bebebe));
            }else {
                mEpisodeBinding.ispay.setVisibility(View.GONE);
            }

            mEpisodeBinding.episodePlayItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String isPay=episode.getIsPay();
                    //付费点击无效
                    if ("1".equals(isPay)) return;

                    if(context instanceof VideoDetailActivity){
                        if ( MoviesApplication.getInstance()
                                .getDownloadManager().selectDownloadJobByMid(episode
                                .getSerialid())) {
                            ToastUtil.showShortToast(
                                    MoviesApplication.getInstance(),
                                    R.string.down_exists);
                        } else {
                            downloadListItems.put(episode.getSerialid(), DownloadJob.WAITING);
                            DownloadEpisodePlayAdapter.this.notifyDataSetChanged();
                            ((VideoDetailActivity)context).downLoadEpisodes(v, index*50+position);
                        }

                    }
                }
            });

            if(downloadListItems.get(episode.getSerialid()) != null){
                mEpisodeBinding.downloadIcon.setVisibility(View.VISIBLE);
                if(downloadListItems.get(episode.getSerialid()) == DownloadJob.COMPLETE){
                    mEpisodeBinding.downloadIcon.setImageResource(R.drawable.download_complete);
                } else {
                    mEpisodeBinding.downloadIcon.setImageResource(R.drawable.download_ing);
                }
            } else {
                mEpisodeBinding.downloadIcon.setVisibility(View.GONE);
            }

        }
    }



    public void setEpisodes(ArrayList<Episode> episodes) {
        this.episodes=episodes;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return episodes.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    public interface OnItemClickListener {
        void onItemClick(View view, final int i);
    }
    private SparseArray<Boolean> isHasClarity;
    private void initData() {
        isHasClarity = new SparseArray<Boolean>();
        if (null != episodes && episodes.size() > 0) {
            for (int i = 0; i < episodes.size(); i++) {
                isHasClarity.put(i, true);//默认存在
            }
        }
    }

    public boolean getIsHasClarity(int position) {
        boolean result = false;
        if (null != isHasClarity && isHasClarity.size() > position) {
            result = isHasClarity.get(position);

        }
        return result;
    }
    // 根据下载数据库中的数据更新已下载标记
    public void  updateDownloadedFlagByDB() {
        downloadListItems.clear();
        ArrayList<DownloadJob> downloadList = MoviesApplication.getInstance()
                .getDownloadManager().getAllDownloads();

        if (null != downloadList && downloadList.size() > 0) {
            DownloadEntity entity;
            String downloadSerialsId;
            for (int i = 0; i < downloadList.size(); i++) {
                entity = downloadList.get(i).getEntity();
                if (null != entity) {
                    downloadSerialsId = entity.getId();
                    if (null != episodes && episodes.size() > 0 && !TextUtils.isEmpty(downloadSerialsId)) {
                        String serialId;
                        for (int j = 0; j < episodes.size(); j++) {
                            serialId = episodes.get(j).getSerialid();
                            if (downloadSerialsId.equals(serialId)) {
                                downloadListItems.put(serialId, downloadList.get(i).getStatus());
                            }
                        }
                    }
                }
            }
        }
        this.notifyDataSetChanged();
    }
    public void setmSelectProder(String mSelectProder) {
        if (TextUtils.isEmpty(mSelectProder)) {
            this.mSelectProder = "";
        } else {
            this.mSelectProder = mSelectProder;
        }
        notifyDataSetChanged();
    }


}

